const userService = require('../service/user.service')
const jwt = require('jsonwebtoken')
const {PRIVATE_KEY} = require('../app/config')

class UserController {
  //注册
  async create(ctx, next) {
    const user = ctx.request.body

    try {
      const result = await userService.create(user)
      // 初始化用户信息
      const userinfo = await userService.getUserByName(user.username)
      const userId = userinfo[0].id
      const initInfo = await userService.initUserinfo(user.username, userId)
      ctx.success({
        msg: '注册成功'
      })
    } catch (error) {
      console.log(error.message)
    }
  }

  // 登陆
  async login(ctx, next) {
    const {id, username} = ctx.user
    const token = jwt.sign({id, username}, PRIVATE_KEY, {
      expiresIn: 60*60*24,
      algorithm: 'RS256'
    })

    ctx.success({
      data: {id, username, token},
      msg: '登陆成功'
    })
  }

  // 获取账户信息
  async getUser(ctx, next) {
    const userId = ctx.user.id
    ctx.success({
      data: {
        userId
      }
    })
  }
}

module.exports = new UserController()